#include <iostream>
#include <unistd.h>
#include <cstring>
#include <cassert>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int fd[2];
    if (pipe(fd) == -1) {
        perror("pipe");
        return 1;
    }

    pid_t id = fork();
    if (id < 0) {
        perror("fork");
        return 1;
    }

    if (id == 0) { // child process
        close(fd[1]); // 关闭写端
        char buffer[1024];
        while (true) {
            ssize_t cnt = read(fd[0], buffer, sizeof(buffer));
            if (cnt <= 0) break; // 读取结束或出错
            std::cout << "我是子进程# pid: " << getpid() << " cnt: " << cnt << std::endl;
            std::cout << buffer << std::endl;
        }
        close(fd[0]); // 关闭读端
        exit(0);
    } else { // parent process
        close(fd[0]); // 关闭读端
        const char* message = "Hello from parent!";
        ssize_t write_flag = write(fd[1], message, strlen(message) + 1); // +1 for null terminator
        assert(write_flag >= 0);
        close(fd[1]); // 关闭写端
        waitpid(id, nullptr, 0); // 等待子进程结束
    }
    return 0;
}